package lxq.asia;

import java.util.HashSet;
import java.util.Set;

/**
 * 稀疏数组
 */
public class SparseArray {

    public static void toSparse(int[][] normal){
        int usedCount=0;
        Set<int[]> usedSet=new HashSet<>();
        for (int i = 0; i < normal.length; i++) {
            for (int j = 0; j < normal[i].length; j++) {
                if (normal[i][j]!=0) {
                    usedCount++;
                    usedSet.add(new int[]{i,j,normal[i][j]});
                }
            }
        }
        System.out.println("总共有 "+usedCount+" 个有效数据");
//        System.out.println(Arrays.toString(usedSet.toArray()));
        int[][] sparse=new int[usedCount+1][3];
        sparse[0][0]=11;
        sparse[0][1]=11;
        sparse[0][2]=usedCount;
        int index=1;
        for (int[] data : usedSet) {
            sparse[index][0] = data[0];
            sparse[index][1] = data[1];
            sparse[index][2] = data[2];
            index++;
        }
        for (int[] ints : sparse) {
            for (int anInt : ints) {
                System.out.print("\t"+anInt);
            }
            System.out.println();
        }
        toNormal(sparse);
//        try {
//            ObjectOutputStream objectOutputStream=new ObjectOutputStream (new FileOutputStream("d:/map.data"));
//            objectOutputStream.writeObject(sparse);
//            objectOutputStream.flush();
//            objectOutputStream.close();
//            ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream("d:/map.data"));
//            int[][] sparseFromFile= (int[][]) objectInputStream.readObject();
//            toNormal(sparseFromFile);
//            objectInputStream.close();
//        } catch (IOException | ClassNotFoundException e) {
//            throw new RuntimeException(e);
//        }

    }
    
    static public void toNormal(int[][] sparse){
        int[][] normal =new int[sparse[0][0]][sparse[0][1]];
        for (int i = 1; i < sparse.length; i++) {
            normal[sparse[i][0]][sparse[i][1]]=sparse[i][2];
        }
        System.out.println("还原成原数组");
        for (int[] ints : normal) {
            for (int anInt : ints) {
                if (anInt==0) System.out.print("□  ");
                else System.out.print("■  ");
//                System.out.print(anInt+"\t");
            }
            System.out.println();
        }
    }
}
